import uuid
# from flaskapp.model.db import db, Dictionary
# from sqlalchemy.exc import SQLAlchemyError
from flaskapp.model.mongo import db
from datetime import datetime
import logging
from bson import ObjectId
# Setup logging
logger = logging.getLogger(__name__)


def insert(category: str, key: str, value: str) -> bool:
    try:
        current_datetime = datetime.now()
        # info = Dictionary(id=str(uuid.uuid4()),pid=None, category=category,
        #                   key=key, value=value, timestamp=current_datetime)
        # db.session.add(info)
        # db.session.commit()
        info = {"pid":None, "category":category,
                          "key":key, "value":value, "timestamp":current_datetime}
        db.dictionary.insert_one(info)
        logger.info(f"Inserted dict with id: {info.id}")
        return True
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error inserting dict: {e}")
        return False


def delete(id: str) -> bool:
    try:
        # info = Dictionary.query.get(id)
        info = db.dictionary.find_one({"_id":ObjectId(id)})
        if info:
            # db.session.delete(info)
            # db.session.commit()
            db.dictionary.delete_one({"_id":ObjectId(id)})
            logger.info(f"Deleted dict with id: {info._id}")
            return True
        logger.warning(f"User with id: {id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error deleting dict: {e}")
        return False


def get(page: int = 1, per_page: int = 10, category: str = None) -> dict:
    try:
        logger.info(
            f"Fetching dicts for page: {page}, per_page: {per_page}, category: {category}")
        # query = Dictionary.query.order_by(Dictionary.timestamp.desc())
        
        # if category is None:
        #     pass
        # else:
        #     query = query.filter(Dictionary.category == category)
        # pagination = query.paginate(
        #     page=page, per_page=per_page, error_out=False)
        # items = [info.to_dict() for info in pagination.items]
        total=db.dictionary.count_documents({})
        dic_page = db.dictionary.find().sort("timestamp").limit(per_page).skip(per_page*(page-1))
        items=[]
        for r in dic_page:
            items.append(r)
            
        logger.info(
            f"Retrieved {len(items)} dicts from page {page}, total items: {total}")
        return {
            "items": items,
            "total": total
        }
    except BaseException as e:
        logger.error(f"Error retrieving dicts: {e}")
        return {
            "items": [],
            "total": 0
        }
    
def dict_category_kv(category: str = None) -> dict:
    try:
        logger.info(f"Fetching dictionary items for category: {category}")
        # query = Dictionary.query
        dic_page=db.dictionary.find({"category":category})
        # if category:
        #     query = query.filter(Dictionary.category == category)
        
        items = []
        for r in dic_page:
            items.append(r)
        
        result = {item["key"]: item["value"] for item in items}
        
        logger.info(f"Retrieved {len(result)} dictionary items for category: {category}")
        return result
    except BaseException as e:
        logger.error(f"Error retrieving dictionary items: {e}")
        return {}
